package com.xnfh.home.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorManager
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.CoordinateConverter
import com.amap.api.maps.MapView
import com.amap.api.maps.UiSettings
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.TileOverlayOptions
import com.amap.api.maps.model.TileProvider
import com.amap.api.maps.model.UrlTileProvider
import com.xnfh.common.MyApplication
import com.xnfh.home.R
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URL

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/17 16:29
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/17 16:29
 * @UpdateRemark: 更新说明
 */
object EnclosureMapUtil {

    private var aMap: AMap? = null
    private var uiSettings: UiSettings? = null
    private var myLocationStyle: MyLocationStyle? = null
    private var mSM: SensorManager? = null
    private var mSensor: Sensor? = null
    private var searchMarker: Marker? = null


    fun init(
        context: Context,
        mapView: MapView,
        onMapClickListener: AMap.OnMapClickListener,
        onMarkerDragListener: AMap.OnMarkerDragListener,
        onMapLoadedListener: AMap.OnMapLoadedListener,
        onMyLocationChangeListener: AMap.OnMyLocationChangeListener,
        onCameraChangeListener: AMap.OnCameraChangeListener,
        onMarkerClickListener: AMap.OnMarkerClickListener
    ): AMap? {
        if (aMap == null) {
            aMap = mapView.map
        }
        aMap!!.mapType = AMap.MAP_TYPE_NORMAL
        aMap!!.showMapText(false)
        aMap!!.animateCamera(CameraUpdateFactory.zoomTo(18f))
        uiSettings = aMap!!.uiSettings
        uiSettings?.isScaleControlsEnabled = true
        uiSettings?.isTiltGesturesEnabled = false
        uiSettings?.isZoomControlsEnabled = false
        uiSettings?.isRotateGesturesEnabled = false
        aMap!!.setOnMapClickListener(onMapClickListener)
        aMap!!.setOnMarkerDragListener(onMarkerDragListener)
        aMap!!.setOnMapLoadedListener(onMapLoadedListener)
        aMap!!.setOnCameraChangeListener(onCameraChangeListener)

        myLocationStyle = MyLocationStyle()
        myLocationStyle?.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
        myLocationStyle?.radiusFillColor(Color.TRANSPARENT)
        myLocationStyle?.strokeColor(Color.TRANSPARENT)
        myLocationStyle?.interval(5000)
        myLocationStyle?.myLocationIcon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.arrows_img))
        myLocationStyle?.showMyLocation(false)
        aMap!!.myLocationStyle = myLocationStyle
        aMap!!.setOnMyLocationChangeListener(onMyLocationChangeListener)
        aMap!!.setOnMarkerClickListener(onMarkerClickListener)
        mSM = context.getSystemService(AppCompatActivity.SENSOR_SERVICE) as SensorManager
        mSensor = mSM?.getDefaultSensor(Sensor.TYPE_ORIENTATION)
        aMap!!.maxZoomLevel = 18f
        val url =
            "https://api.mapbox.com/v4/mapbox.satellite/%d/%d/%d@2x.png?access_token=pk.eyJ1Ijoid2N6aGFzaGkiLCJhIjoiY2tiMWp2OHZ0MDFodzJzcDdsOWUyd2kyNSJ9.ldTBPCfTwOfcO4KPyQhdWg"
        val tileProvider: TileProvider = object : UrlTileProvider(256, 256) {
            override fun getTileUrl(x: Int, y: Int, zoom: Int): URL? {
                try {
                    return URL(String.format(url, zoom, x, y))
                } catch (e: MalformedURLException) {
                    e.printStackTrace()
                }
                return null
            }
        }
        if (tileProvider != null) {
            aMap!!.addTileOverlay(
                TileOverlayOptions()
                    .tileProvider(tileProvider)
                    .diskCacheEnabled(false)
                    .diskCacheDir("/storage/emulated/0/amap/cache")
                    .diskCacheSize(100000)
                    .memoryCacheEnabled(false)
                    .memCacheSize(100000)
            )
        }

        val url2 =
            "http://t0.tianditu.gov.cn/DataServer?T=cia_w&tk=42713dd342d128b5e5f8a9bdad589c7c&x=%d&y=%d&l=%d&s=Galile"
        val tileProvider2: TileProvider = object : UrlTileProvider(256, 256) {
            override fun getTileUrl(x: Int, y: Int, zoom: Int): URL? {
                try {
                    return URL(String.format(url2, x, y, zoom))
                } catch (e: MalformedURLException) {
                    e.printStackTrace()
                }
                return null
            }
        }
        if (tileProvider2 != null) {
            aMap!!.addTileOverlay(
                TileOverlayOptions()
                    .tileProvider(tileProvider2)
                    .diskCacheEnabled(false)
                    .diskCacheDir("/storage/emulated/0/amap/cache")
                    .diskCacheSize(100000)
                    .memoryCacheEnabled(false)
                    .memCacheSize(100000)
            )
        }
        return aMap
    }

    fun wgs84ToGcj02(context: Context,sourceLatLng: LatLng): LatLng? {
        val converter =
            CoordinateConverter(context)
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS)
        // sourceLatLng待转换坐标点 LatLng类型
        converter.coord(sourceLatLng)
        // 执行转换操作
        return converter.convert()
    }


    fun addMarker(latLng: LatLng) {
        if (searchMarker == null) {
            // 在地图上添一组图片标记（marker）对象，并设置是否改变地图状态以至于所有的marker对象都在当前地图可视区域范围内显示
            val markerOptions = MarkerOptions()
            // 设置Marker覆盖物的位置坐标。Marker经纬度坐标不能为Null，坐标无默认值
            markerOptions.position(latLng)
            // 设置Marker覆盖物是否可见
            markerOptions.visible(true)
            markerOptions.icon(BitmapDescriptorFactory.fromResource(com.xnfh.common.R.mipmap.icon_search_marker))
            // 设置Marker覆盖物是否可拖拽
            markerOptions.draggable(false)
            searchMarker = aMap!!.addMarker(markerOptions)
        } else {
            searchMarker?.position = latLng
        }
    }

    fun getFileByBitmap(context: Context,bitmap: Bitmap): File {
        val bao = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bao)
        val time = System.currentTimeMillis()
        val file = File(context.filesDir.absolutePath + "/" + time + ".jpg")
        try {
            file.createNewFile()
            val fos = FileOutputStream(file)
            val `is`: InputStream = ByteArrayInputStream(bao.toByteArray())
            var x = 0
            val b = ByteArray(1024 * 100)
            while (`is`.read(b).also { x = it } != -1) {
                fos.write(b, 0, x)
            }
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return file
    }

    fun destory(){
        aMap = null
        uiSettings = null
        myLocationStyle = null
        mSM = null
        mSensor = null
    }


}